package com.xiyuan.controller.common;

import com.xiyuan.constant.CommonConstant;
import com.xiyuan.constant.MessageConstant;
import com.xiyuan.pojo.result.Result;
import com.xiyuan.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
public class FileUploadController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws Exception {
        try {
            //指定Oss保存的文件路径 如 项目名/2024/10/13/文件名
            String objectName = CommonConstant.PROJECT_NAME+"/"+LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //保证文件名唯一性
            String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            //上传文件
            String url = aliOssUtil.upload(file.getBytes(), objectName + newFileName);
            return Result.success(url);
        }catch(Exception e) {
           return Result.error(MessageConstant.UPLOAD_FAIL);
        }

    }
}

